package com.gensdai.leliang.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.OrderCommentProductListAdapter;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.gensdai.leliang.view.ColoredRatingBar;
import com.gensdai.leliang.view.NoScrollListView;
import com.gensdai.leliang.view.Toaster;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 评论
 * Created by zsxx on 2017/8/15.
 */

public class PostComment extends BaseActivity {

    public static final String EXTRA_OBJS = "OBJECTS";
    public static final String EXTRA_ID = "ORDERID";


    @BindView(R.id.productComRating)
    ColoredRatingBar productComRating;
    @BindView(R.id.productRatingText)
    TextView productRatingText;
    @BindView(R.id.logisticRating)
    ColoredRatingBar logisticRating;
    @BindView(R.id.LogisticRatingText)
    TextView LogisticRatingText;
    @BindView(R.id.serviceRating)
    ColoredRatingBar serviceRating;
    @BindView(R.id.serviceRatingText)
    TextView serviceRatingText;
    @BindView(R.id.productInfo)
    NoScrollListView productInfo;


    String orderid = "";
    OrderCommentProductListAdapter adapter;
    List<BaseParse.OrderAttributeMapBean> list = null;
    KProgressHUD hud;

    @Override
    protected String getTitleStr() {
        return "发布评价";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_post_comment;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.post_comment_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_post_comment:
                getJsonStr();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        orderid = getIntent().getStringExtra(EXTRA_ID);
        list = (List<BaseParse.OrderAttributeMapBean>) getIntent().getSerializableExtra(EXTRA_OBJS);

        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在处理...")
                .setCancellable(true)
                .setAnimationSpeed(1)
                .setDimAmount(0.5f);

        initList();

        productComRating.setOnRatingBarChangeListener(new ColoredRatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(ColoredRatingBar ratingBar, float rating, boolean fromUser) {
                productRatingText.setText(changeText((int) rating));
            }
        });
        logisticRating.setOnRatingBarChangeListener(new ColoredRatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(ColoredRatingBar ratingBar, float rating, boolean fromUser) {
                LogisticRatingText.setText(changeText((int) rating));
            }
        });
        serviceRating.setOnRatingBarChangeListener(new ColoredRatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(ColoredRatingBar ratingBar, float rating, boolean fromUser) {
                serviceRatingText.setText(changeText((int) rating));
            }
        });
    }

    private void initList() {
        adapter = new OrderCommentProductListAdapter(this);
        productInfo.setAdapter(adapter);
        adapter.initAdd(list);
    }


    public String changeText(int rating) {
        String str = "满意";
        switch (rating) {
            case 1:
            case 2:
                str = "不满意";
                break;
            case 3:
                str = "一般";
                break;
            case 4:
                str = "满意";
                break;
            case 5:
                str = "非常满意";
                break;
            default:
                break;
        }

        return str;
    }


    public void getJsonStr() {

        String uno = PreferencesUtils.getStringPreference(this, OrderPreper2Activity.prefreceName, "userno", "");

        if (productComRating.getRating() <= 0) {
            Toaster.showOneToast("亲，为我们的商品评个分把！");
            return;
        }
        if (logisticRating.getRating() <= 0) {
            Toaster.showOneToast("亲，为我们的物流评个分把！");
            return;
        }
        if (serviceRating.getRating() <= 0) {
            Toaster.showOneToast("亲，为我们的服务评个分把！");
            return;
        }


        JsonObject obj = new JsonObject();
        JsonArray array = new JsonArray();
        for (int i = 0; i < list.size(); i++) {
            JsonObject oj = new JsonObject();
            BaseParse.OrderAttributeMapBean att = list.get(i);
            oj.addProperty("productAttributeId", att.productAttributeId);
            oj.addProperty("orderAttributeId", att.orderAttributeId);
            oj.addProperty("commentInfo", att.commentStr);
            array.add(oj);
        }
        obj.add("commentArray", array);
        Log.d("commentArray",array.toString());

        Map<String, String> params = new HashMap<>();
        params.put("clientType", AppApplication.ClientType);
        params.put("orderNo", orderid);
        params.put("userNo", uno);
        params.put("productScore", productComRating.getRating() + "");
        params.put("serviceScore", serviceRating.getRating() + "");
        params.put("logisticsScore", logisticRating.getRating() + "");
        params.put("commentArray", array.toString());

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().POSTCOMMENT(params))
                .compose(this.<BaseParse<String>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
                        if (hud != null) {
                            hud.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new Observer<BaseParse<String>>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull BaseParse<String> p) {
                        if (hud != null && hud.isShowing()) {
                            hud.dismiss();
                        }
                        if (p.success) {
                            Toaster.showOneToast(p.message);
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            Toaster.showOneToast(p.message);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        if (hud != null && hud.isShowing()) {
                            hud.dismiss();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (hud != null && hud.isShowing()) {
                            hud.dismiss();
                        }
                    }
                });
    }
}
